import "package:ducafe_ui_core/ducafe_ui_core.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:flutter_mobx/flutter_mobx.dart";
import "package:hinge/common/index.dart";
import "package:hinge/store/release_store.dart";
import "package:hinge/store/root_store.dart";
import "package:url_launcher/url_launcher.dart";

// 自定义画笔实现虚线框效果
class DashedBorderPainter extends CustomPainter {
  final double strokeWidth;
  final Color color;
  final double dashWidth;
  final double dashSpace;
  final double radius;

  DashedBorderPainter({
    required this.strokeWidth,
    required this.color,
    required this.dashWidth,
    required this.dashSpace,
    required this.radius,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint =
        Paint()
          ..color = color
          ..strokeWidth = strokeWidth
          ..style = PaintingStyle.stroke;

    // 创建一个虚线效果
    final Path dashedPath = Path();

    // 左上角弧线
    dashedPath.moveTo(radius, 0);
    dashedPath.lineTo(size.width - radius, 0);

    // 右上角弧线
    dashedPath.arcToPoint(
      Offset(size.width, radius),
      radius: Radius.circular(radius),
      clockwise: true,
    );

    // 右边
    dashedPath.lineTo(size.width, size.height - radius);

    // 右下角弧线
    dashedPath.arcToPoint(
      Offset(size.width - radius, size.height),
      radius: Radius.circular(radius),
      clockwise: true,
    );

    // 底边
    dashedPath.lineTo(radius, size.height);

    // 左下角弧线
    dashedPath.arcToPoint(
      Offset(0, size.height - radius),
      radius: Radius.circular(radius),
      clockwise: true,
    );

    // 左边
    dashedPath.lineTo(0, radius);

    // 左上角弧线，完成闭合
    dashedPath.arcToPoint(
      Offset(radius, 0),
      radius: Radius.circular(radius),
      clockwise: true,
    );

    // 绘制虚线
    final dashPath = Path();
    final dashLength = dashWidth + dashSpace;
    final pathMetrics = dashedPath.computeMetrics();

    for (var metric in pathMetrics) {
      double distance = 0.0;
      bool draw = true;

      while (distance < metric.length) {
        final segmentLength = draw ? dashWidth : dashSpace;
        final end = distance + segmentLength;

        if (draw) {
          final extractPath = metric.extractPath(
            distance,
            end > metric.length ? metric.length : end,
          );
          dashPath.addPath(extractPath, Offset.zero);
        }

        distance = end;
        draw = !draw;
      }
    }

    canvas.drawPath(dashPath, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

class ReleasePage extends StatefulWidget {
  const ReleasePage({super.key});

  @override
  State<ReleasePage> createState() => _ReleasePageState();
}

class _ReleasePageState extends State<ReleasePage> {
  final _rootStore = RootStore();
  final _releaseStore = ReleaseStore();
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  // 新增推荐状态字段，初始值为 true
  bool _isRecommend = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  // 打开EULA链接
  void _openEulaLink() async {
    const url = 'https://www.example.com/eula';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      EasyLoading.showError('Could not open EULA');
    }
  }

  // 处理发布
  void _handleRelease() async {
    // 发布时将推荐状态同步到 store
    _releaseStore.setIsRecommend(_isRecommend);
    final result = await _releaseStore.submit();
    if (result) {
      EasyLoading.showSuccess('Published successfully');
      context.pop();
    } else {
      if (!_releaseStore.isValid) {
        EasyLoading.showError('Please complete all required fields');
      } else {
        EasyLoading.showError('Failed to publish');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.50, -0.00),
            end: Alignment(0.50, 1.00),
            colors: [const Color(0xFFA794FD), const Color(0xFFFFEFFA)],
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
            child: Column(
              children: [
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        context.pop();
                      },
                      child: Icon(
                        IconFont.back,
                        color: Colors.white,
                        size: 28.sp,
                      ),
                    ),
                    SizedBox(width: 20.w),
                    Text(
                      "Release",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Spacer(),
                  ],
                ),
                SizedBox(height: 30.h),
                Container(
                  width: double.infinity,
                  height: 72.h,
                  decoration: ShapeDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.49, -0.00),
                      end: Alignment(0.49, 0.97),
                      colors: [
                        const Color(0xFFC0ABFF),
                        const Color(0xFFDBCAFF),
                      ],
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(44.50),
                    ),
                    shadows: [
                      BoxShadow(
                        color: Color(0x549266C7),
                        blurRadius: 4,
                        offset: Offset(0, 4),
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      SizedBox(width: 10.w),
                      Image.asset(
                        AssetsImages.upload,
                        width: 63.w,
                        height: 63.h,
                      ),
                      SizedBox(width: 10.w),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Sync to home",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          Text(
                            "page recommendations",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                      Spacer(),
                      // 推荐开关按钮
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            _isRecommend = !_isRecommend;
                          });
                        },
                        child: AnimatedContainer(
                          duration: Duration(milliseconds: 300),
                          width: 68.w,
                          height: 40.h,
                          decoration: ShapeDecoration(
                            color:
                                _isRecommend
                                    ? const Color(0xFFBD88FF)
                                    : const Color(0xFFBDBDBD),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(28),
                            ),
                            shadows: [
                              BoxShadow(
                                color: Color(0x549266C7),
                                blurRadius: 4,
                                offset: Offset(0, 4),
                                spreadRadius: 0,
                              ),
                            ],
                          ),
                          child: Center(
                            child: AnimatedSwitcher(
                              duration: Duration(milliseconds: 300),
                              transitionBuilder: (
                                Widget child,
                                Animation<double> animation,
                              ) {
                                return ScaleTransition(
                                  scale: animation,
                                  child: child,
                                );
                              },
                              child: Text(
                                _isRecommend ? "Open" : "Closed",
                                key: ValueKey<bool>(_isRecommend),
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 20.w),
                    ],
                  ),
                ),

                SizedBox(height: 36.h),

                // 图片上传区域
                Observer(
                  builder:
                      (_) => GestureDetector(
                        onTap: () => _releaseStore.selectImage(context),
                        child:
                            _releaseStore.perfumeImage != null
                                ? Container(
                                  width: double.infinity,
                                  height: 231.h,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(12.r),
                                    image: DecorationImage(
                                      image: FileImage(
                                        _releaseStore.perfumeImage!,
                                      ),
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                )
                                : Stack(
                                  children: [
                                    Container(
                                      width: double.infinity,
                                      height: 231.h,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                        color: Color(0x33856DEB),
                                      ),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            'Upload pictures',
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 18.sp,
                                              fontWeight: FontWeight.w500,
                                              fontFamily: "Inter",
                                            ),
                                          ),
                                          SizedBox(height: 8.h),
                                          Text(
                                            'Click the button below to switch the\nupload type.',
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                              color: Colors.white.withOpacity(
                                                0.8,
                                              ),
                                              fontSize: 14.sp,
                                              fontFamily: "Inter",
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    // 虚线边框绘制层
                                    CustomPaint(
                                      painter: DashedBorderPainter(
                                        strokeWidth: 1.5,
                                        color: Color(0xFF856DEB),
                                        dashWidth: 6,
                                        dashSpace: 3,
                                        radius: 12,
                                      ),
                                      child: SizedBox(
                                        width: double.infinity,
                                        height: 231.h,
                                      ),
                                    ),
                                  ],
                                ),
                      ),
                ),

                SizedBox(height: 20.h),

                // 分类选择
                Observer(
                  builder:
                      (_) => Container(
                        width: double.infinity,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            _buildCategoryButton('Strong fragrance'),
                            _buildCategoryButton('Eau de Toilette'),
                            _buildCategoryButton('Woody'),
                          ],
                        ),
                      ),
                ),

                SizedBox(height: 36.h),

                // 标题输入框
                Container(
                  height: 56.h,
                  decoration: BoxDecoration(
                    color: Color(0x33856DEB),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: TextField(
                    controller: _titleController,
                    onChanged: _releaseStore.setTitle,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontFamily: "Inter",
                    ),
                    decoration: InputDecoration(
                      hintText: 'title',
                      hintStyle: TextStyle(
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16.sp,
                        fontFamily: "Inter",
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(horizontal: 16.w),
                    ),
                  ),
                ),

                SizedBox(height: 12.h),

                // 描述输入框
                Container(
                  height: 120.h,
                  decoration: BoxDecoration(
                    color: Color(0x33856DEB),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: TextField(
                    controller: _descriptionController,
                    onChanged: _releaseStore.setDescription,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontFamily: "Inter",
                    ),
                    maxLines: 5,
                    textInputAction: TextInputAction.done,
                    onSubmitted: (_) {
                      FocusScope.of(context).unfocus();
                    },
                    decoration: InputDecoration(
                      hintText: 'Introduction',
                      hintStyle: TextStyle(
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16.sp,
                        fontFamily: "Inter",
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                  ),
                ),

                Spacer(),

                // 底部按钮区
                Row(
                  children: [
                    // Reset按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          _releaseStore.reset();
                          _titleController.clear();
                          _descriptionController.clear();
                        },
                        child: Container(
                          height: 50.h,
                          decoration: BoxDecoration(
                            border: Border.all(
                              color: const Color(0xFFBD88FF),
                              width: 1,
                            ),
                            borderRadius: BorderRadius.circular(25.r),
                          ),
                          child: Center(
                            child: Text(
                              "Reset",
                              style: TextStyle(
                                color: const Color(0xFFBD88FF),
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),

                    SizedBox(width: 12.w),

                    // Release按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: _handleRelease,
                        child: Container(
                          height: 50.h,
                          decoration: BoxDecoration(
                            color: const Color(0xFFBD88FF),
                            borderRadius: BorderRadius.circular(25.r),
                            boxShadow: [
                              BoxShadow(
                                color: const Color(0xFFBD88FF).withOpacity(0.3),
                                blurRadius: 8,
                                offset: Offset(0, 4),
                              ),
                            ],
                          ),
                          child: Center(
                            child: Text(
                              "release",
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),

                Spacer(),

                // EULA链接
                GestureDetector(
                  onTap: _openEulaLink,
                  child: Text(
                    'EULA',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: const Color(0xFF6B6B6B),
                      fontSize: 15.sp,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                      decoration: TextDecoration.underline,
                      height: 0.80,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 分类按钮构建
  Widget _buildCategoryButton(String category) {
    return Observer(
      builder: (_) {
        final isSelected = _releaseStore.category == category;
        return GestureDetector(
          onTap: () => _releaseStore.setCategory(category),
          child: Text(
            category,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: isSelected ? Color(0xFF150555) : Color(0xFF9B90C6),
              fontSize: 18.sp,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
            ),
          ),
        );
      },
    );
  }
}
